<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
class Common extends Controller
{
    public function _initialize()
    {
        
		parent::_initialize();
        $wechatModel = controller('wechat');
        $jsapiTicket = $wechatModel->getJsapiTicket();
        $timestamp = time();
        $nonceStr = $wechatModel->getRandCode();
        $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];//当前url全路径
        // echo '路径1：'.$url;
        $signature = 'jsapi_ticket='.$jsapiTicket.'&noncestr='.$nonceStr.'&timestamp='.$timestamp.'&url='.$url;
        $signature = sha1($signature);
        $this->assign('appid',sysconf('wx_appid'));
        $this->assign('nonceStr',$nonceStr);
        $this->assign('signature',$signature);
        $this->assign('timestamp',$timestamp);
        if(strpos($url,'parentId') || strpos($url,'parentid')){
            $link = $url;
        }
        $parentId = input('param.parentId');
        if (!session('userId') || !Db::name('user')->where('id',session('userId'))->find()){
            $link = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"];

            $wechatModel->getCode($parentId);
        } else {
            $link = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"].'?parentId='.session('userId');

            $wechatModel->bindUserParent(session('userId'),$parentId);
        }
        $this->assign('link',$link);
    }
    /*获取商品信息*/
    public function getGoodsData($is_top=false,$is_rec=false,$is_special=false,$limit='')
    {
        $where = ['status'=>0];
        $is_top ? $where['is_top'] = 1 : '';
        $is_rec ? $where['is_rec'] = 1 : '';
        $is_special ? $where['is_special'] = 1 : '';
        $limit ? $limit : '';
        return Db::name('goods')->where($where)->order('sort desc,add_time desc')->limit($limit)->select();
    }
    /*
     * base64 上传图片
     * */
    public function uploadBase($base)
    {
        $base64_img = trim($base);
        if (empty($base64_img)) {
            return ['code'=>1,'msg'=>'请选择图片'];
        }
        $savepath = 'public/upload/'.date("Ymd");//存放在当前目录的upload文件夹下
        if (!file_exists($savepath)) {
            @mkdir($savepath);
        }
        $savename = date('YmdHis',time()).rand('11111','99999');
        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
            $type = $result[2];
            if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
                $path = $savepath.'/'.$savename.".".$type;
                if (file_put_contents($path, base64_decode(str_replace($result[1], '', $base64_img)))) {
                    return ['code'=>0,'path'=>'/'.$path];
                } else {
                    return ['code'=>1,'msg'=>'上传失败'];
                }
            } else {
                return ['code'=>1,'msg'=>'文件格式错误'];
            }
        } else {
            return ['code'=>1,'msg'=>'上传文件格式错误'];
        }
    }
    /*
    ***聚合数据（JUHE.CN）短信API服务接口PHP请求示例源码
    ***DATE:2015-05-25
    */
    public function sendSms()
    {
        $mobile = input('param.mobile');
        header('content-type:text/html;charset=utf-8');
        $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL
        $code = rand('100000','999999');
        cookie($mobile, $code, 3000);
        $smsConf = array(
            'key'   => sysconf('sms_appkey'), //您申请的APPKEY
            'mobile'    => $mobile, //接受短信的用户手机号码
            'tpl_id'    => sysconf('sms_tpl_id'), //您申请的短信模板ID，根据实际情况修改
            'tpl_value' =>'#code#='.$code //您设置的模板变量，根据实际情况修改
        );
        $content = request_post($sendUrl,$smsConf); //请求发送短信
        if($content){
            $result = json_decode($content,true);
            $error_code = $result['error_code'];
            if($error_code == 0){
                json_msg(0,"短信发送成功");
            }else{
                $msg = $result['reason'];
                json_msg(1,"短信发送失败:$msg");
            }
        }else{
            json_msg(1,"请求发送短信失败");
        }
    }
    /*根据省份获取城市*/
    public function getCitys()
    {
        $provinceid = input('param.provinceid');
        $data = Db::name('cities')->where('provinceid',$provinceid)->select();
            json_msg_data(0,'成功',$data);

    }
    /*根据城市获取区域*/
    public function getAreas()
    {
        $cityid = input('param.cityid');
        $data = Db::name('areas')->where('cityid',$cityid)->select();
        json_msg_data(0,'成功',$data);
    }
    public function createQrcode($content,$filename,$logo='public/upload/logo.jpg')
    {
        vendor('phpqrcode.phpqrcode');

        $object = new \QRcode();

        $errorCorrectionLevel = 'H';//容错级别
        $matrixPointSize = 5;//生成图片大小
        //生成二维码图片
        $object->png($content, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
        //已经生成的原始二维码图
        if ($logo) {
            $QR = imagecreatefromstring(file_get_contents($filename));
            $logo = imagecreatefromstring(file_get_contents($logo));
            $QR_width = imagesx($QR);//二维码图片宽度
            $QR_height = imagesy($QR);//二维码图片高度
            $logo_width = imagesx($logo);//logo图片宽度
            $logo_height = imagesy($logo);//logo图片高度
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width/$logo_qr_width;
            $logo_qr_height = $logo_height/$scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            //重新组合图片并调整大小
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
                $logo_qr_height, $logo_width, $logo_height);

        }
        imagepng($QR, $filename);
        return '/'.$filename;
        //输出图片
    }
}